package com.huatai.vba.dal.jdbc;

import java.lang.reflect.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SqlUtils {

	public static <T> String generateSql(T t) throws NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		Class clazz = t.getClass();
		String className = clazz.getSimpleName();
		Field[] fields = clazz.getDeclaredFields();
		if (fields == null || fields.length == 0)
			return null;
		StringBuffer sb = new StringBuffer();
		StringBuffer sb1 = new StringBuffer();
		for (Field field : fields) {
			String name = field.getName();
			sb.append(",").append(name);
			Method m = clazz.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1));
			Object value = m.invoke(t);
			if (value instanceof String) {
				sb1.append(",'").append(value).append("'");
			} else if (value instanceof Date) {
				String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format((Date) value);
				sb1.append(",to_date('").append(yyyyMMddHHmmss).append("','yyyymmddhh24miss') ");
			} else {
				sb1.append(",").append(value);
			}
		}
		String columnSql = sb.toString().substring(1);
		String valueSql = sb1.toString().substring(1);
		return "insert into " + className + "(" + columnSql + ")values(" + valueSql + ")";
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		User user = new User();
		user.setId(1);
		user.setUserName("faneui");
		user.setPassword("121212");
		user.setLoginTime(new Date());
		System.out.println(SqlUtils.generateSql(user));
	}

}
